package jackson.sensitive;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Objects;

/**
 * 数据脱敏
 * https://blog.csdn.net/qq_35067322/article/details/117719404
 */
public class SensitiveJsonSerializer extends JsonSerializer<String> implements ContextualSerializer {
    private SensitiveStrategy strategy;

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (StringUtils.hasLength(value)) {
            gen.writeString(strategy.desensitizer().apply(value));
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        Sensitive sensitive = property.getAnnotation(Sensitive.class);
        // sensitive = property.getContextAnnotation(Sensitive.class);
        if (Objects.nonNull(sensitive) && Objects.equals(String.class, property.getType().getRawClass())) {
            this.strategy = sensitive.strategy();
            return this;
        }
        return prov.findValueSerializer(property.getType(), property);
    }
}